/* \$Id: product_list.js 425 2012-06-20 06:13:35Z bobcat $ */

// put options in numerical order
function sortOptions() {
  J('select').each(function() {
    var items = this.options.length;
    var tmpArray = new Array(items);
    for (i = 0; i < items; i += 1) {
      tmpArray[i] = new Option(this.options[i].text, this.options[i].value);
    }
    tmpArray.sort(function(a, b) {
      return (parseFloat(a.text) - parseFloat(b.text));
    });
    for (i = 0; i < items; i++) {
      this.options[i] = new Option(tmpArray[i].text, tmpArray[i].value);
    }
  });
}

// update cart link to reflect item count
function updateCartQuantity() {
  var quantity = 0;
  var cart = ultraCart.getCart();
  J.each(cart.items, function(key, value) {
    quantity += value.quantity;
  });
  if (quantity > 0) {
    J('span#cart').html('Cart (' + quantity + ')');
  }
}

J(document).ready(function() {

  var tabberOptions = {'manualStartup': true};

  tabberAutomatic(tabberOptions);
  J('div.tabberlive').fadeIn('slow');
  J('div.loading').css('background-image', 'none');
  ultraCart.init(cartConfig);
  if (!J.browser.msie) {
    sortOptions();    
  }

  // select should display info for child product / hide others
  J('select').change(function() {
    var childID = J(this).val().replace(/\./g, '_');
    var JProduct = J(this).parentsUntil('.product_list');
    var JBuyBox = J(this).parents('.buy_box');
    JProduct.find('.non-default, .default').hide();
    if (childID === 'DFLT') {
      JProduct.find('.default').show();
      JBuyBox.find('input').attr('disabled', true);
      JBuyBox.find('.form.price').text('');
    } else {
      JProduct.find('.' + childID).show();
      JBuyBox.find('input').removeAttr('disabled');
      JBuyBox.find('input.numeric').trigger('change');
    }
  });

  // update price on quantity change
  J('input.numeric').change(function() {
    var unitCost, id, quantity, vdId, tierIndex, cost;
    if (J(this).val() !== '' && parseInt(J(this).val()) !== 0) {
      quantity = parseInt(J(this).val());
    } else {
      quantity = 1;
      J(this).val('1');
    }
    vdId = J(this).parents('.buy_box').find('select').val();
    if (vdId) {
      id = '.volume_discounts.' + vdId.replace(/\./g, '_');
    } else {
      id = '.volume_discounts';
    }
    tierIndex = 0;
    J(this).parents('.product').find(id).find('tr').each(function() {
      if (tierIndex !== 0) {
        var lower, tierQuan, tierCost, lower, upper;
        tierQuan = J(this).find('.vd-quantity').html();
        tierCost = parseFloat(J(this).find('.vd-cost').html().substring(1));
        if (tierQuan !== 'Any') {
          lower = parseInt(tierQuan);
          if (tierQuan.indexOf('+') === -1) {
            upper = parseInt(tierQuan.substring(tierQuan.indexOf('-') + 1));
            if (quantity >= lower && quantity <= upper) {
              unitCost = tierCost;
              return false;
            }
          } else if (quantity >= lower) {
            unitCost = tierCost;
            return false;
          } else {
            alert('bad quantity');
          }
        } else {
          unitCost = tierCost;
        }
      }
      tierIndex += 1;
    });
    cost = '$' + (quantity * unitCost).toFixed(2);
    J(this).parents('.buy_box').find('.form.price').text(cost);
  });

  // apply numeric only input for quantity field
  if (typeof jQuery.fn.numeric === 'function') {
    J('input.numeric').numeric();
  }

  // apply light box to each gallery
  J(function() {
    J('.product_image').each(function() {
      J(this).find('a').lightBox({fixedNavigation: true});
    });
  });

  // pdf link should open in new page
  J('.pdf').click(function() {window.open(this.href); return false;});

  // add to cart bind
  J('div.buy_box > form').submit(function(event) {
    try {
      var JStatus, itemId, quantity, items, errors;
      event.preventDefault();
      JStatus = J(this).find('td.status');
      JStatus.html('');
      if (J(this).find('select').length === 0) {
        itemId = J(this).find('input[name=add]').attr('value').replace(/\s/g, '');
      } else {
        itemId = J(this).find('select').val();
      }
      quantity = J(this).find('input[name=quantity]').val().replace(/\s/g, '');
      items = {itemId: itemId, quantity: quantity};
      errors = ultraCart.addItems([items]);
      if (errors.length === 0) {
        if (quantity > 1) {
          JStatus.html('Added ' + quantity + ' items to cart');
        } else {
          JStatus.html('Added ' + quantity + ' item to cart');
        }
      } else {
        JStatus.html(errors);
      }
      JStatus.show();
      updateCartQuantity();
    } catch (e) {
      handleError('Add to cart' + e);
    }
  });

});
